import React, { memo, useContext, useState } from "react";
import {
  Button,
  Divider,
  Dropdown,
  Menu,
  message,
  Modal,
  Popconfirm,
  TreeSelect,
} from "antd";
import { Link } from "react-router-dom";
import { menuDataAdd } from "../config";
import { renderTreeNodes } from "@pkgs/Layout/utils";
import { NsTreeContext } from "@pkgs/Layout/Provider";
import { FormattedMessage } from "react-intl";
import _ from "lodash";
import type { Dispatch, SetStateAction } from "react";
import type { DiscoveryTableListType } from "../interface";
import request from "@pkgs/request";
import api from "@common/api";

type Props = {
  selectedData?: DiscoveryTableListType[];
  type: string;
  refresh: () => void;
  deleteList: (type: string, ids: number[]) => Promise<void>;
  setSelectedIds: Dispatch<SetStateAction<any[]>>;
  setSelectedRows: Dispatch<SetStateAction<DiscoveryTableListType[]>>;
};

const BatchOperate: React.FC<Props> = (props) => {
  const [visible, setVisible] = useState(false);
  const [selectNodeId, setSelectNodeId] = useState<number>();

  const nstreeContext = useContext(NsTreeContext);
  const treeData = _.get(nstreeContext, "data.treeNodes");

  const {
    selectedData,
    type,
    deleteList,
    refresh,
    setSelectedRows,
    setSelectedIds,
  } = props;

  const batchDelete = () => {
    let ids: number[] = [];
    if (selectedData) {
      ids = selectedData.map((item) => {
        return item.id;
      });
    }
    deleteList(type, ids);
    setSelectedIds([]);
    setSelectedRows([]);
    refresh();
  };

  const handleBatchCloneToOtherNid = (
    selectedData: any,
    type: string,
    selectNodeId: number | undefined
  ) => {
    let data: any = [];
    selectedData.forEach((item: any) => {
      delete item.id;
      const itemData = Object.assign(item, { nid: selectNodeId });
      const obj = {
        type: type,
        data: itemData,
      };
      data.push(obj);
    });
    request(api.discovery, {
      method: "POST",
      body: JSON.stringify(data),
    }).then(() => {
      message.success("克隆成功");
    });
  };

  const addMenu = (
    <Menu>
      {menuDataAdd.map((item) => (
        <Menu.Item key={item.key}>
          <Link to={`/prometheus/discovery/add/${item.label}`}>
            {item.name}
          </Link>
        </Menu.Item>
      ))}
    </Menu>
  );

  const batchMenu = (
    <Menu>
      <Menu.Item key="delete">
        <Popconfirm
          title={<FormattedMessage id="table.delete.sure" />}
          onConfirm={() => batchDelete()}
        >
          <a>删除</a>
          <Divider type="vertical" />
        </Popconfirm>
      </Menu.Item>
      <Menu.Item key="clone">
        <a onClick={() => showModal()}>克隆</a>
      </Menu.Item>
    </Menu>
  );

  function showModal() {
    setVisible(true);
  }

  function handleOk() {
    handleBatchCloneToOtherNid(selectedData, type, selectNodeId);
    setSelectedIds([]);
    setSelectedRows([]);
    setVisible(false);
    refresh();
  }
  function handleCancel() {
    setVisible(false);
  }

  return (
    <div className="discover_menu_batch">
      <Dropdown overlay={addMenu}>
        <Button style={{ width: 80 }}>创建</Button>
      </Dropdown>
      <Divider type="vertical" />
      <Dropdown overlay={batchMenu} disabled={selectedData?.length === 0}>
        <Button style={{ width: 80 }}>批量操作</Button>
      </Dropdown>
      <Modal
        title="请选择克隆路径"
        visible={visible}
        onOk={handleOk}
        onCancel={handleCancel}
        width="550px"
      >
        <TreeSelect
          style={{ width: 500 }}
          showSearch
          allowClear
          treeNodeFilterProp="path"
          treeNodeLabelProp="path"
          onChange={(value: number) => {
            setSelectNodeId(value);
          }}
          dropdownStyle={{ maxHeight: 400, overflow: "auto" }}
        >
          {renderTreeNodes(treeData, "treeSelect")}
        </TreeSelect>
      </Modal>
    </div>
  );
};

export default memo(BatchOperate);
